package sctu.edu.java.year2016.team01.xuhanmei.day20160619;

import java.io.*;

/**
 * Created by Administrator on 2016/6/19.
 */
public class FileUtil {
    public static void copyFile(String srcpath, String destpath) throws IOException {//对文件的拷贝
        //建立联系源，存在且为文件，目的地，，文件可以不存在

        copyFile(new File(srcpath), new File(destpath));
    }

    public static void copyFile(File src, File dest) throws IOException {
        if (!src.isFile()) {
            System.out.println("只能拷贝文件");
            throw new IOException("只能拷贝文件");

        }

        //选择流

        InputStream is = new FileInputStream(src);
        OutputStream os = new FileOutputStream(dest);

        //文件的拷贝，读取与写出
        byte[] bytes = new byte[1024];
        int len = 0;

        while (-1 != (len = is.read(bytes))) {
            os.write(bytes, 0, len);
        }
        os.flush();//刷新

        //先开的后关
        os.close();
        is.close();
    }



    public static void copyDir(String srcpath, String destpath){//对文件夹的拷贝
        File src = new File(srcpath);
        File dest = new File(destpath);
        copyDir(src,dest);
        copydirDetail(src, dest);
    }



    public static void copyDir(File src, File dest){
        if (src.isDirectory()) {
            dest=new File(dest,src.getName());
        }
        copydirDetail(src, dest);
    }




    private static void copydirDetail(File src, File dest) {
        if (src.isFile()) {
            try {
                FileUtil.copyFile(src, dest);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (src.isDirectory()) {
            dest.mkdirs();
            for (File sub : src.listFiles()) {
                copydirDetail(sub, new File(dest, sub.getName()));
            }
        }
    }
}
